package Executor;

import java.util.List;

import parser.Node;
import parser.Root;

public class Minimization {

	public Minimization(){
		
	}
	
	public List<Root> minimize(List<Root> rootList){
		for (Root root : rootList){
			minimize((Node) root);
		}
		return rootList;
	}

	private void minimize(Node node) {
		if (!node.getChild().isEmpty()){
			List<Node> childList = node.getChild();
			if (childList.size() == 1) {
				minimize(childList.get(0));
			} else {
				for (int i = 0; i < childList.size(); i++) {
					Node currChild = childList.get(i);
					for (int j = i + 1; j < childList.size(); j++) {
						Node otherChild = childList.get(j);
						if (currChild.getSimList().contains(otherChild)) {
							node.removeChild(currChild);
							i--;
							break;
						} else {
							minimize(currChild);
						}

					}
				}
			}
		}
		
		if (!node.getDecendant().isEmpty()){
			List<Node> decedantList = node.getDecendant();
			if (decedantList.size()==1) minimize(decedantList.get(0));
			else {
				for (int i = 0; i < decedantList.size(); i++) {
					Node currDecedant = decedantList.get(i);
					for (int j = i + 1; j < decedantList.size(); j++) {
						Node otherDecedant = decedantList.get(j);
						// if otherChild is in sim(currDecedant) or
						// auganc(sim(currDecedant))
						if (currDecedant.getSimList().contains(otherDecedant)
								|| currDecedant.getAuganc().contains(
										otherDecedant)) {
							node.removeDecendant(currDecedant);
							i--;
							break;
						} else {
							minimize(currDecedant);
						}
						// else recursive call minimize(currDecedant)
					}
				}
			}
		}
		
	}
}
